using System;
using System.Collections.Generic;
using MSOffice = Microsoft.Office.Core;
using MSOutlook = Microsoft.Office.Interop.Outlook;

namespace Microsoft.Sample.Outlook.Utility
{
    /// <summary>
    /// Simple adapter class for the explorer and inspector window objects. Provides a generic mechanism to access
    /// the common properties and methods of both window object types. Also adapts the event signatures to include a 
    /// reference to the object firing the event
    /// </summary>
    internal sealed class WindowAdapter
    {
        object _window;

        public event EventHandler Activate;
        public event EventHandler Close;
        public event EventHandler SelectionChange;

        public WindowAdapter(MSOutlook.Explorer explorer)
        {
            _window = explorer;

            MSOutlook.ExplorerEvents_10_Event events = (MSOutlook.ExplorerEvents_10_Event)explorer;
            events.Activate += delegate()
            {
                Activate(this, null);
            };

            events.Close += delegate()
            {
                Close(this, null);
            };

            events.SelectionChange += delegate()
            {
                SelectionChange(this, null);
            };

            events.FolderSwitch += delegate()
            {
                SelectionChange(this, null);
            };
        }

        public WindowAdapter(MSOutlook.Inspector inspector)
        {
            _window = inspector;

            MSOutlook.InspectorEvents_10_Event events = (MSOutlook.InspectorEvents_10_Event)inspector;
            events.Activate += delegate()
            {
                Activate(this, null);
            };

            events.Close += delegate()
            {
                Close(this, null);
            };
        }

        public MSOffice.CommandBars CommandBars
        {
            get
            {
                //The CommandBars collection is not available on newly constructed explorer windows. 
                //In this scenario, accessing the CommandBars collection throws an exception. 
                //Here, we trap the exception and return null instead.
                try
                {
                    return (MSOffice.CommandBars)_window.GetType().InvokeMember(
                        "CommandBars",
                        System.Reflection.BindingFlags.GetProperty,
                        null, _window, null);
                }
                catch (System.Reflection.TargetInvocationException)
                {
                    return null;
                }
            }
        }

        public MSOutlook.Explorer Explorer
        {
            get { return _window as MSOutlook.Explorer; }
        }

        public MSOutlook.Inspector Inspector
        {
            get { return _window as MSOutlook.Inspector; }
        }
    }


}
